package p.ithorns.sample.tracer.jaeger;

import io.opentracing.Span;
import io.opentracing.SpanContext;
import io.opentracing.Tracer;
import io.opentracing.util.GlobalTracer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * TraceInterceptor
 *
 * @author HtL
 * @date 2025/3/21 14:54
 * @since 1.0.0
 */
@Slf4j
public class TraceInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Tracer tracer = GlobalTracer.get();
        Span span = tracer.activeSpan();
        if (span != null) {
            SpanContext context = span.context();
            String traceId = context.toTraceId();
            TraceContext.set(traceId);
            log.info("TraceInterceptor preHandle,generate traceId is:{}", traceId);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("TraceInterceptor afterCompletion,ready to clean traceId:{}", TraceContext.get());
        TraceContext.clean();
    }
}